package in.iqing.module.data.task;

import android.content.Context;
import android.os.Handler;

import org.apache.commons.io.FileUtils;

import java.io.File;

import in.iqing.Constants;
import in.iqing.module.data.filter.CoverFileFilter;

/**
 * Created by neavo on 2015/5/21.
 */

public class ClearCacheTask implements Runnable {

	private Context ctx;
	private Handler handler;
	private ICallback callback;

	public ClearCacheTask(Handler handler, Context ctx, ICallback callback) {
		this.ctx = ctx;
		this.handler = handler;
		this.callback = callback;
	}

	@Override
	public void run() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				callback.onStart();
			}
		});

		File[] bookDirs = Constants.DATADIR.listFiles();

		for (File bookDir : bookDirs != null ? bookDirs : new File[0]) {
			if (bookDir.isDirectory()) {
				File[] coverFiles = bookDir.listFiles(new CoverFileFilter());

				for (File cover : coverFiles != null ? coverFiles : new File[0]) {
					FileUtils.deleteQuietly(cover);
				}
			}
		}

		FileUtils.deleteQuietly(ctx.getCacheDir());
		FileUtils.deleteQuietly(ctx.getExternalCacheDir());

		handler.post(new Runnable() {

			@Override
			public void run() {
				callback.onFinish();
			}
		});
	}

	public interface ICallback {

		void onStart();

		void onFinish();
	}
}
